package com.ruoyi.huanjing.tool;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 海洋参数二进制文件解析器
 * （默认使用小端序，不对外暴露字节序设置，由工具类内部固定）
 */
public class OceanParamBinaryParser {
    // 可视化类型枚举（三大数据类型）
    public enum VisualizeType {
        BASIC_PARAMS,                // 海面基本特性
        WAVE_HEIGHT_SPECTRUM,        // 波高谱
        WAVE_DIRECTION_SPECTRUM      // 波向谱
    }

    private final String filePath;
    private byte[] fileData;
    // 固定使用小端序（不再提供set方法修改）
    private static final ByteOrder DEFAULT_BYTE_ORDER = ByteOrder.LITTLE_ENDIAN;

    // 存储解析后的数据（按类型区分）
    private final Map<VisualizeType, Object> parsedDataMap = new HashMap<>();

    public OceanParamBinaryParser(String filePath) {
        this.filePath = filePath;
    }

    /**
     * 读取文件内容到字节数组
     */
    public boolean readFile() {
        try (FileInputStream fis = new FileInputStream(new File(filePath));
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }
            this.fileData = bos.toByteArray();
            return true;
        } catch (IOException e) {
            System.err.println("文件读取失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 按类型解析数据（核心方法，使用固定小端序）
     */
    public void parse(VisualizeType type, boolean parseAll) {
        if (fileData == null) {
            throw new IllegalStateException("请先调用readFile()读取文件");
        }

        // 固定使用小端序（工具类内部默认）
        ByteBuffer buffer = ByteBuffer.wrap(fileData).order(DEFAULT_BYTE_ORDER);

        try {
            // 1. 解析海面基本特性（所有类型都需先解析基础参数）
            Map<String, Double> basicParams = new HashMap<>();
            basicParams.put("significantWaveHeight", buffer.getDouble());
            basicParams.put("maxWaveHeight", buffer.getDouble());
            basicParams.put("avgWaveHeight", buffer.getDouble());
            basicParams.put("waveDirection", buffer.getDouble());
            basicParams.put("wavePeriod", buffer.getDouble());
            basicParams.put("currentSpeed", buffer.getDouble());
            basicParams.put("currentDirection", buffer.getDouble());
            basicParams.put("seaSurfaceTemp", buffer.getDouble());
            basicParams.put("seaStateLevel", buffer.getDouble());
            parsedDataMap.put(VisualizeType.BASIC_PARAMS, basicParams);

            // 2. 解析谱数据（按需解析）
            int dataLength = buffer.getInt();
            List<Double> frequencyData = new ArrayList<>(dataLength);
            for (int i = 0; i < dataLength; i++) {
                frequencyData.add(buffer.getDouble());
            }

            // 波高谱
            if (parseAll || type == VisualizeType.WAVE_HEIGHT_SPECTRUM) {
                List<Double> waveHeightData = new ArrayList<>(dataLength);
                for (int i = 0; i < dataLength; i++) {
                    waveHeightData.add(buffer.getDouble());
                }
                Map<String, List<Double>> heightSpectrum = new HashMap<>();
                heightSpectrum.put("xAxis", frequencyData);
                heightSpectrum.put("yAxis", waveHeightData);
                parsedDataMap.put(VisualizeType.WAVE_HEIGHT_SPECTRUM, heightSpectrum);
            } else {
                buffer.position(buffer.position() + 8 * dataLength); // 跳过不解析的字节
            }

            // 波向谱
            if (parseAll || type == VisualizeType.WAVE_DIRECTION_SPECTRUM) {
                List<Double> waveDirectionData = new ArrayList<>(dataLength);
                for (int i = 0; i < dataLength; i++) {
                    waveDirectionData.add(buffer.getDouble());
                }
                Map<String, List<Double>> directionSpectrum = new HashMap<>();
                directionSpectrum.put("xAxis", frequencyData);
                directionSpectrum.put("yAxis", waveDirectionData);
                parsedDataMap.put(VisualizeType.WAVE_DIRECTION_SPECTRUM, directionSpectrum);
            } else {
                buffer.position(buffer.position() + 8 * dataLength); // 跳过不解析的字节
            }

        } catch (Exception e) {
            throw new RuntimeException("解析失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取基本特性数据
     */
    public Map<String, Double> getBasicParamsDTO() {
        return (Map<String, Double>) parsedDataMap.get(VisualizeType.BASIC_PARAMS);
    }

    /**
     * 获取谱数据（波高谱/波向谱）
     */
    public Map<String, List<Double>> getSpectrumDTO(VisualizeType type) {
        if (type != VisualizeType.WAVE_HEIGHT_SPECTRUM && type != VisualizeType.WAVE_DIRECTION_SPECTRUM) {
            throw new IllegalArgumentException("仅支持波高谱和波向谱类型");
        }
        return (Map<String, List<Double>>) parsedDataMap.get(type);
    }
}